package org.soc.timesheet.server.domain.service;

import java.util.Calendar;
import java.util.Set;

import org.apache.commons.lang3.RandomStringUtils;
import org.soc.timesheet.custom.annotation.AOPLogger;
import org.soc.timesheet.custom.annotation.AOPLogger.LoggerLevel;
import org.soc.timesheet.custom.annotation.AOPLogger.LoggerWhen;
import org.soc.timesheet.domain.Emails;
import org.soc.timesheet.domain.Users;
import org.soc.timesheet.domain.UsersLogged;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class CommonServiceImpl implements CommonService {

	@Autowired
	UsersService usersService;

	@Autowired
	EmailsService emailsService;

	@Autowired
	UsersLoggedService usersLoggedService;

	@Autowired
	TokenTypeService tokenTypeService;

	@Transactional
	@Override
	@AOPLogger(name = "service.COMMON", loggerLevel = LoggerLevel.INFO, loggerWhen = {
			LoggerWhen.ON_ENTER, LoggerWhen.ON_EXIT })
	public UsersLogged createUser(Users users) throws Exception {
		try {
			final Users u = usersService.saveUsers(users);
			Set<Emails> emails = users.getEmailss();
			for (Emails em : emails) {
				Emails e = new Emails();
				e.setIdUsers(u);
				e.setEmail(em.getEmail());
				emailsService.saveEmails(e);

			}
			final String token = RandomStringUtils.randomAlphanumeric(200);

			UsersLogged logged = new UsersLogged();
			logged.setId(RandomStringUtils.randomAlphanumeric(100));
			logged.setIdTokenType(tokenTypeService.findByTypeDesc("RECOVER")
					.getId());
			logged.setIdUser(u);
			logged.setLastAccess(Calendar.getInstance());
			logged.setToken(token);
			logged.setSessioId("RECOVER_"+RandomStringUtils.randomAlphanumeric(20));

			usersLoggedService.saveUsersLogged(logged);
			return logged;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

}
